package com.example.equipment.service.impl;

import com.example.equipment.bean.Product;
import com.example.equipment.bean.ProductMac;
import com.example.equipment.bean.User;
import com.example.equipment.bean.config.OpenApiResult;
import com.example.equipment.bean.enums.ResultEnum;
import com.example.equipment.bean.po.BatchPo;
import com.example.equipment.bean.po.CheckMacPo;
import com.example.equipment.bean.vo.ProductMacExt;
import com.example.equipment.mapper.ProductMacMapper;
import com.example.equipment.mapper.ProductMapper;
import com.example.equipment.service.ProductMacService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class ProductMacServiceImpl implements ProductMacService {

    @Autowired
    private ProductMacMapper productMacMapper;
    @Autowired
    private ProductMapper productMapper;

    @Value("${spring.profiles.active:pro}")
    private String environment;

    /**
     * 导入
     *
     * @param file
     * @param productId
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OpenApiResult importMac(MultipartFile file, Integer productId, User user) {

        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null || product.getEnableFlag().equals(false)) {
            return OpenApiResult.fail("产品id不存在");
        }

        Set<String> serialNoSet = new LinkedHashSet<>();
        StringBuilder sb = new StringBuilder();

        try (InputStream inputStream = file.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String str = null;
            int count = 0;
            while ((str = reader.readLine()) != null) {
                // 输出文件内容
                if (str != null && !StringUtils.isEmpty(str.trim())) {
                    serialNoSet.add(str.trim());
                    count++;
                }
            }
            log.info("本次导入数据共={},剔除重复数据共={}", count, serialNoSet.size());
            //检查数据库是否已经存在数据
            serialNoSet.forEach(x -> {
                ProductMac productMac = productMacMapper.selectByProductNoAndSn(product.getProductNo(), x);
                if (productMac != null) {
                    sb.append(",").append(x);
                }
            });
            if (sb.length() > 0) {
                return OpenApiResult.fail("本次导入失败，此产品下SN号重复，重复数据=" + sb.substring(1));
            }
            //导入
            serialNoSet.forEach(x -> {
                ProductMac mac = new ProductMac();
                mac.setProductId(productId);
                mac.setProductNo(product.getProductNo());
                mac.setSerialNo(x);
                mac.setCreateBy(user.getName());
                mac.setCreateTime(new Date());
                mac.setUpdateBy(user.getName());
                mac.setUpdateTime(mac.getCreateTime());
                productMacMapper.insertSelective(mac);
            });
        } catch (IOException e) {
            log.error("读取文件异常,e=", e);
            return new OpenApiResult(ResultEnum.EXCEL_FILE_READ_EXCEPTION);
        }
        return OpenApiResult.ok();
    }

    @Override
    public void cleanById(BatchPo po, String updateUserName) {
        for (Integer id : po.getId()) {
            ProductMac tmp = new ProductMac();
            tmp.setId(id);
            tmp.setMacAddress("");
            tmp.setUpdateBy(updateUserName);
            tmp.setUpdateTime(new Date());
            productMacMapper.updateByPrimaryKeySelective(tmp);
        }
    }

    @Override
    public void deleteById(BatchPo po, String updateUserName) {
        for (Integer id : po.getId()) {
            ProductMac tmp = productMacMapper.selectByPrimaryKey(id);
            if (tmp == null) {
                continue;
            }
            tmp.setEnableFlag(false);
            tmp.setUpdateBy(updateUserName);
            tmp.setUpdateTime(new Date());
            tmp.setDelMark(tmp.getId());
            productMacMapper.updateByPrimaryKeySelective(tmp);
        }
    }

    /**
     * 记录mac
     *
     * @param po
     * @return
     */
    @Override
    public OpenApiResult checkMac(CheckMacPo po) {
        Product product = new Product();
        product.setProductNo(po.getProductNo());
        List<Product> list = productMapper.selectBySelective(product);
        if (CollectionUtils.isEmpty(list)) {
            return OpenApiResult.fail("未找到编号为：" + po.getProductNo() + "的产品");
        }
        //测试环境
        if (!"pro".equalsIgnoreCase(environment)) {
            ProductMac mac = productMacMapper.selectByProductNoAndSnAndMac(po.getProductNo(), po.getSerialNo(), po.getMacAddress());
            if (mac == null) {
                product = list.get(0);
                mac = new ProductMac();
                mac.setProductId(product.getId());
                mac.setProductNo(product.getProductNo());
                mac.setSerialNo(po.getSerialNo());
                mac.setMacAddress(po.getMacAddress());
                mac.setCreateBy("user report");
                mac.setCreateTime(new Date());
                mac.setUpdateBy(mac.getCreateBy());
                mac.setUpdateTime(mac.getUpdateTime());
                productMacMapper.insertSelective(mac);
            }else {
                mac.setUpdateTime(new Date());
                mac.setUpdateBy("user report");
                productMacMapper.updateByPrimaryKeySelective(mac);
            }
            return OpenApiResult.ok(true);
        }

        ProductMac mac = productMacMapper.selectByProductNoAndSn(po.getProductNo(), po.getSerialNo());
        if (mac == null) {
            return OpenApiResult.fail("未找到编号为：" + po.getProductNo() + "设备流水号为：" + po.getSerialNo() + "的记录");
        }
        if ("".equals(mac.getMacAddress())) {
            //insert
            mac.setMacAddress(po.getMacAddress());
            productMacMapper.updateByPrimaryKeySelective(mac);
            return OpenApiResult.ok(true);
        }
        if (po.getMacAddress().equalsIgnoreCase(mac.getMacAddress())) {
            return OpenApiResult.ok(true);
        } else {
            return OpenApiResult.ok(false);
        }
    }

    @Override
    public List<ProductMacExt> getList(String productNo, String productName, String serialNo) {
        return productMacMapper.getListByProductNoAndName(productNo, productName, serialNo);
    }


}
